package com.supor.aiot.common.ui.view;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.mobile.nebula.appcenter.download.H5DownloadRequest;
import com.alipay.mobile.nebula.provider.H5AppProvider;
import com.alipay.mobile.nebula.util.H5Utils;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.mpaas.nebula.adapter.api.MPNebula;
import com.mpaas.nebula.adapter.api.MPTinyBaseIntermediateLoadingView;
import com.mpaas.nebula.adapter.api.MpaasNebulaDownloadCallback;
import com.mpaas.nebula.adapter.api.MpaasNebulaInstallCallback;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.AppAgent;

import androidx.annotation.Nullable;

public class TinyStartupLoadingView extends MPTinyBaseIntermediateLoadingView {

    private TextView tvAppName;
    private TextView tvTips;
    private ImageView ivAppIcon;
    private int count = 0;
    String appId;


    public TinyStartupLoadingView(Context context) {
        super(context);
        init();
    }

    public TinyStartupLoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TinyStartupLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Logc.i("init: appinfo: ");
        LayoutInflater.from(getContext()).inflate(R.layout.tiny_loading, this, true);
        tvAppName = findViewById(R.id.tv_app);
        ivAppIcon = findViewById(R.id.iv_app_icon);
        tvTips = findViewById(R.id.tv_tips);
        ((CustomTitleBar) findViewById(R.id.title)).setIvLeftOnClickListener(v -> {
            Activity host = getLoadingActivity();
            if (host != null) {
                host.finish();
            }
        });
    }

    /**
     * 初始化时调用，会传入小程序的应用ID，其他信息如名称、应用图标、版本，可能为空
     */
    @Override
    public void initView(AppInfo info) {
        // tvAppName.setText(info.appName);
        if (info != null) {
            Logc.i("initView: appinfo: " + info.appId + ", version: " + info.version + ", appName: " + info.appName);
            appId = info.appId;
        } else {
            Logc.i("initView: appinfo: null");
            appId = AppAgent.tinyAppId;
        }
    }

    /**
     * 获取小程序失败时调用
     */
    @Override
    public void onError() {
        Logc.i("app load onError");
        downloadApp();
    }

    /**
     * 手动下载小程序
     */
    private void downloadApp() {
        H5AppProvider provider = H5Utils.getProvider(H5AppProvider.class.getName());
        if (provider == null) {
            Logc.i("downloadApp: provider is null");
            startApp();
            return;
        }
        com.alipay.mobile.nebula.appcenter.model.AppInfo appInfo = provider.getAppInfo(appId);
        if (appInfo == null) {
            Logc.i("downloadApp: appinfo is null");
            startApp();
            return;
        }
        Logc.i("downloadApp: appinfo: " + appInfo.toString());
        // 某版本应用离线包是否已经下载完成
        boolean isAvailable = provider.isAvailable(appId, appInfo.version);
        // 某版本应用是否已经安装
        boolean isInstalled = provider.isInstalled(appId, appInfo.version);
        Logc.d("downloadApp: isAvailable: " + isAvailable + ", isInstalled: " + isInstalled);
        if (isInstalled) {
            startApp();
        } else if (isAvailable) {
            installApp();
        } else {
            // startApp();
            Logc.i("downloadApp: start download...");
            MPNebula.downloadApp(appId, new MpaasNebulaDownloadCallback(){
                @Override
                public void onAppHasDownloaded(String appId, String version) {
                    super.onAppHasDownloaded(appId, version);
                    Logc.d("onAppHasDownloaded: " + appId + ", version: " + version);
                    installApp();
                }

                // 未回调
                @Override
                public void onPrepare(@Nullable H5DownloadRequest h5DownloadRequest) {
                    super.onPrepare(h5DownloadRequest);
                    if (h5DownloadRequest != null) {
                        Logc.d("onPrepare: " + h5DownloadRequest.getDownloadUrl());
                    }
                }

                // 未回调
                @Override
                public void onProgress(@Nullable H5DownloadRequest h5DownloadRequest, int progress) {
                    super.onProgress(h5DownloadRequest, progress);
                    Logc.d("onProgress: " + progress);
                }

                // 未回调
                @Override
                public void onCancel(@Nullable H5DownloadRequest h5DownloadRequest) {
                    super.onCancel(h5DownloadRequest);
                    Logc.d("onCancel: ");
                    startApp();
                }

                @Override
                public void onFinish(@Nullable H5DownloadRequest h5DownloadRequest, String savePath) {
                    super.onFinish(h5DownloadRequest, savePath);
                    Logc.d("onFinish: savePath: " + savePath);
                    installApp();
                }

                @Override
                public void onFailed(@Nullable H5DownloadRequest h5DownloadRequest, int errorCode,
                                     String errorMsg) {
                    super.onFailed(h5DownloadRequest, errorCode, errorMsg);
                    Logc.d("onFailed: errorCode= " + errorCode + ", errorMsg= " + errorMsg);
                    downloadApp();
                }
            });
        }
    }

    /**
     * 手动安装小程序
     */
    private void installApp() {
        MPNebula.installApp(appId, new MpaasNebulaInstallCallback(){
            @Override
            public void onResult(boolean success, boolean isPatch) {
                super.onResult(success, isPatch);
                Logc.d("onResult: success: " + success + ", isPatch: " + isPatch);
                if (success) {
                    startApp();
                } else {
                    downloadApp();
                }
            }

            @Override
            public void onAppHasInstalled(String appId, String version) {
                super.onAppHasInstalled(appId, version);
                Logc.d("onAppHasInstalled: version: " + version);
                startApp();
            }
        });
    }

    /**
     * 启动小程序
     */
    private void startApp() {
        Bundle bundle = AppAgent.tinyBundle;
        if (bundle == null) {
            bundle = new Bundle();
            bundle.putBoolean("needAnimInTiny", true);
            String query = "urlType="+ Uri.encode("0")+"&redirectUrl="+ Uri.encode("0");
            bundle.putString("query",query); //设置参数
        }

        MPNebula.startApp(AppAgent.tinyAppId, bundle);
        Logc.i("app load again...");
        tvAppName.postDelayed(() -> {
            Activity host = getLoadingActivity();
            if (host != null) {
                host.finish();
            }
        }, 500);
    }

    /**
     * 拉取到小程序应用信息时调用，可获取应用ID，名称、图标和版本信息
     */
    @Override
    public void update(AppInfo info) {
        // tvAppName.setText(info.appName);
        if (info != null) {
            Logc.i("update: appinfo: " + info.appId + ", version: " + info.version + ", appName: " + info.appName);
        } else {
            Logc.i("update: appinfo: null");
        }
    }
}
